package org.theqcp.wow.sim.gui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;

import javax.swing.SwingUtilities;

public class EnhSimCharFile {

    protected final File file;

    public EnhSimCharFile(String fileName) {
	this(new File(fileName));
    }

    public EnhSimCharFile(File file) {
	this.file = file;
    }

    public void read( EnhSimGUIFrame enhSimFrame ) throws IOException {
	BufferedReader reader = new BufferedReader(new FileReader(file));
	String line, dataPointName, value;
	DataPoint dataPoint;

	while( null != (line = reader.readLine()) ) {
	    if( line.length() >= 32 ) {
		dataPointName = line.substring(0, 31).trim();

		if( dataPointName.equals("int") ) {
		    dataPointName = "Int";
		} else if( !line.startsWith("###") ) {
		    dataPoint = DataPoint.valueOf(dataPointName);
		    value = line.substring(31);

		    if( value.contains("/") ) {
			enhSimFrame.setDataPoint(dataPoint, value.trim().substring(0, 1));
		    } else {
			enhSimFrame.setDataPoint(dataPoint, value.trim().replaceAll(" ", "_"));
		    }
		}
	    }
	}
    }

    public void write( EnhSimGUIFrame enhSimFrame ) throws IOException {
	BufferedWriter writer = new BufferedWriter(new FileWriter(file));

	String key, value;
	for( Entry<DataPoint, String> entry: enhSimFrame.getDataPoints().entrySet() ) {
	    key = entry.getKey().toString().toLowerCase();
	    value = entry.getValue().toString().toLowerCase();
	    if( enhSimFrame.isTalent(entry.getKey()) ) {
		try {
		    int cur, max;

		    cur = Integer.valueOf(entry.getValue());
		    max = enhSimFrame.getTalentMax(entry.getKey());

		    writer.append(String.format("%-32s%d/%d\r\n", key, cur, max));
		} catch( Throwable e ) {
		    SwingUtilities.invokeLater(new ScrollingExceptionDialog(e));
		}
	    } else {
		writer.append(String.format("%-32s%s\r\n", key, value));
	    }
	}

	writer.flush();
	writer.close();
    }

}
